package com.hxd.mall.utils.open

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import java.io.File
import java.io.FileOutputStream
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import androidx.core.view.marginBottom
import androidx.core.view.marginLeft
import androidx.core.view.marginRight
import androidx.core.view.marginTop
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics

/**
 * Create by yinzhengwei on 2019-11-05
 * @Function
 */
/**
 * View转换为Bitmap图片
 *
 * @param view
 * @return Bitmap
 */
fun convertViewToBitmap(view: View): Bitmap? {
    //创建Bitmap,最后一个参数代表图片的质量.
    val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap
        .Config
        .ARGB_8888)
//    val bitmap = Bitmap.createBitmap(view.context.displayMetrics.widthPixels * 2 / 3, view.height, Bitmap.Config.ARGB_8888)
    //创建Canvas，并传入Bitmap.
    val canvas = Canvas(bitmap)
    canvas.drawColor(Color.TRANSPARENT)
    //View把内容绘制到canvas上，同时保存在bitmap.
    view.draw(canvas)

    return bitmap
}

fun saveBitmap(bitmap: Bitmap, context: Context) {
    var file: File? = null
    val bitName = "temp_${System.currentTimeMillis()}.jpg"
    var fileName = ""

//    if (Build.BRAND.toLowerCase() == "xiaomi") {

//    val dirFile = File(Environment.getExternalStorageDirectory().path + "/DCIM/Camera")
    val dirFile = File(Environment.getExternalStorageDirectory().path + "/Pictures")
    if (!dirFile.exists())
        dirFile.mkdirs()
    fileName = dirFile.absolutePath + File.separator + bitName
//    } else {
//        fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName
//    }
    file = File(fileName)
    if (file.exists()) {
        file.delete()
    }

    val outputStream = FileOutputStream(file)
    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)) {
        outputStream.flush()
        outputStream.close()

        //插入图库
        MediaStore.Images.Media.insertImage(context.contentResolver, file.absolutePath, bitName, null)

        // 发送广播，通知刷新图库的显示
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://$fileName")))

        //插入完相册后删除临时文件
        if (file.exists()) {
            file.delete()
        }

        ToastUtil.showToast("图片已保存到相册，快去分享给好友吧")
    }
}

